package com.example.netty.service.impl;

import com.example.netty.service.TerminalContext;
import com.example.netty.service.TerminalContextService;
import io.netty.channel.ChannelHandlerContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;

import java.net.InetSocketAddress;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by l.wang on 2018/3/28.
 */
@Service
public class TerminalContextServiceImpl implements TerminalContextService {
    private ConcurrentHashMap<String, TerminalContext> deviceContextMap = new ConcurrentHashMap<>();
    private final Log log = LogFactory.getLog(TerminalContextServiceImpl.class);

    @Override
    public boolean getDeviceRouterLogin(ChannelHandlerContext channel) {
        return true;
    }

    /**
     * 数据处理
     * @param channelHandlerContext
     * @param msg
     */
    @Override
    public void channelRead(ChannelHandlerContext channelHandlerContext, Object msg) {
        String remoteIp = ((InetSocketAddress) channelHandlerContext.channel().remoteAddress()).getHostString();
        System.out.println(remoteIp+"--"+msg.toString());
    }

    /**
     * 登录处理
     * @param channel
     * @return
     */
    @Override
    public TerminalContext onConnect(ChannelHandlerContext channel) {
        TerminalContext terminalContext = new TerminalContext();
        terminalContext.setChannel(channel);
        terminalContext.setSessionId(UUID.randomUUID().toString());
        deviceContextMap.put(terminalContext.getSessionId(), terminalContext);
        return terminalContext;
    }

    @Override
    public TerminalContext onDisconnect(ChannelHandlerContext channelHandlerContext) {
        return null;
    }

}
